import logging
import traceback
import webview
import os
from waitress import create_server
from threading import Thread

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s  %(filename)s %(lineno)s: %(levelname)s  %(message)s %(threadName)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)

LOGGER = logging.getLogger(__name__)
os.environ["FLASK_ENV"] = "development"
HOME_PAGE_URL = "http://127.0.0.1:3080/index.html"


window = None


class JsApi:

    def __init__(self) -> None:
        pass

    def closeWindow(self):
        global window
        window.destroy()

    def minWindow(self):
        LOGGER.info("Minimizing window")
        window.minimize()

    def maxWindow(self):
        LOGGER.info("Maximizing window")
        window.maximize()

    def restoreWindow(self):
        LOGGER.info("Restoring window")
        window.restore()


def startFunc(window):
    LOGGER.info("start Func 结束")


class App(object):
    def __init__(self) -> None:
        self.host = "127.0.0.1"
        self.port = 3080
        self.flaskApp = None
        self.flaskServer = None
        self.taskExecutor = None
        self.window = None

    def testFlask(self):
        self.flaskApp = self._initFlask()
        self.flaskApp.run(self.host, self.port, debug=False)

    def run(self):
        try:
            self._initFlask()
            self._initExecutor()
            self._openWindow()
        except Exception as e:
            LOGGER.exception(e)
            LOGGER.error("初始化app失败")

    def _initFlask(self):

        from server.common.init_flask import printEnvInfo
        from server.Application import create_app

        printEnvInfo()

        self.flaskApp = create_app()
        self.flaskServer = create_server(self.flaskApp, host=self.host, port=self.port)
        LOGGER.info("before flask server start")
        Thread(target=self.flaskServer.run).start()
        LOGGER.info("after flask server start")

        # FlaskServer(self.flaskApp, self.host, self.port).start()
        # LOGGER.info("FlaskServer start")

    def _initExecutor(self):
        from server.task_executor import TaskExecutor

        # 异步任务处理线程池
        self.taskExecutor = TaskExecutor(self.flaskApp)
        self.taskExecutor.start()

    def _openWindow(self):

        global window
        webview.settings["ALLOW_DOWNLOADS"] = True
        window = webview.create_window(
            "神笔365 https://365d.ink ",
            HOME_PAGE_URL,
            confirm_close=True,
            frameless=True,
            # fullscreen=True,
            maximized=True,
            # easy_drag=True,
            js_api=JsApi(),
        )
        # wHolder.set(window)
        window.events.closed += self.onWinClosed
        window.events.closing += self.onWinClosing
        window.events.loaded += self.onWinLoaded

        webview.start(startFunc, window)

    def onWinClosed(self):
        LOGGER.info("关闭前")

        if self.taskExecutor is not None:
            self.taskExecutor.shutdown()
            LOGGER.info("已通知线程池关闭") 
        else:
            LOGGER.info("线程池为none，不需要关闭")
        
        LOGGER.info("flaskServer开始关闭") 
        self.flaskServer.close()

        LOGGER.info("关闭完成")

    def onWinClosing(self):
        LOGGER.info("onWinClosing")

    # you can supply optional window argument to access the window object event was triggered on
    def onWinLoaded(self, window):
        LOGGER.info("DOM is ready")

        # unsubscribe event listener
        window.events.loaded -= self.onWinLoaded


if __name__ == "__main__":
    try:
        app = App()
        app.run()

    except Exception as e:
        traceback.print_exception(e)
        print(f"Exception : { e }")
